package com.event.config;

import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * 提供方的配置类
 */
@Configuration
@ComponentScan("com.event")
@SuppressWarnings("ALL")
public class ProviderConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean succ, String exception) {
                if (succ) {
                    //消息已经到达MQ的交换机
                    System.out.println("消息发布成功！");
                } else {
                    //消息发布失败！引入重试 + 补偿机制
                    Message message = correlationData.getReturnedMessage();
                    System.out.println("消息发布失败！" + exception);
                    System.out.println("失败的消息内容：" + message);
                }
            }
        });
    }

    /**
     * 配置一个direct类型的交换机 - 默认名称为event_exchange
     * @return
     */
    @Bean
    public DirectExchange getExchange(){
        return new DirectExchange("event_exchange", true, false);
    }
}
